import axios from 'axios'
import {getTokenHead, getToken, setToken, getRefreshToekn, setRefreshToekn} from './auth'

// create an axios instance
const service = axios.create({
    baseURL: "/api", // url = base url + request url
    // withCredentials: true, // send cookies when cross-domain requests
    timeout: 10000 // request timeout
})

// request interceptor
service.interceptors.request.use(
    config => {
        // do something before request is sent
        config.headers['Authorization'] = getTokenHead() + " " + getToken()
        return config
    },
    error => {
        // do something with request error
        console.log(error)
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    response => {
        if(response.code!==200){
            console.log('ERROR NOT200')
        }
        const res = response.data
        if(res === "未登录或token过期" && getRefreshToekn()!=="undefined"){
            axios({
                url: '/api/auth/oauth/token',
                method: 'post',
                params:{
                    grant_type: 'refresh_token',
                    client_id: 'client-app',
                    client_secret: '123456',
                    refresh_token: getRefreshToekn(),
                }
            }).then(res=>{
                console.log(res)
                setToken(res.data.access_token)
                setRefreshToekn(res.data.refresh_token)
                console.log("重新获得token")
            },err=>{
                console.log(err)
            })
        }
        // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
        if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
            // to re-login
            return Promise.reject(new Error(res.message || 'Error'))
        }
        return res
    },
    error => {
        console.log('err' + error) // for debug
        return Promise.reject(error)
    }
)

export default service
